<?php
class SiteController extends DefaultModuleController {
	// 注册
	public function actionRegister() {
		if($_POST['user']) {
			$user = $_POST['user'];
			if($user['passwd']) {
				$user['passwd'] = md5($user['passwd']);
			}
			// 检验
			$userName = $user['userName'];
			$fax = $user['fax'];
			$email = $user['email'];
			if(!$userName) {
				$this->alert('请输入您的帐号。', 'BACK');
			}
			if(!$fax) {
				$this->alert('请输入您的传真号码。', 'BACK');
			}
			if(!ctype_alnum($userName)) {
				$this->alert('错误，帐号范围a_zA_Z0_9。', 'BACK');
			}
			$userInfo = $this->UserModel->find("userName='$userName'");
			if($userInfo) {
				$this->alert('您输入的帐号已存在，请您重新输入。', 'BACK');
			}
			$userInfo = $this->UserModel->find("email='$email'");
			if($userInfo) {
				$this->alert('您输入的电子邮箱已存在，请您重新输入。', 'BACK');
			}
			if(!is_numeric($user['mobile'])) {
				$this->alert('请输入正确的手机号码。', 'BACK');
			}
			
			if(stripos($user['email'], '@') === FALSE) {
				$this->alert('请输入正确的邮箱。', 'BACK');
			}
			
			// 默认格式
			$user['createdTime'] = $this->time;
			$user['groupId'] = GODHOUSE_GROUP_REGISTER_DEFAULT;
			$this->UserModel->insert($user);
			
			// 发送邮件
			$subject = "恭喜您成为施耐德电气网上商城-波普瑞会员";
			$body = "<style type=text/css> .ex_mail tr td{text-align:left; font-size:12px;} </style>";
			$body .= "<table class=ex_mail width=582 align=center border=0 cellpadding=0 cellspacing=0>";
			$body .= "<thead>";
			$body .= "    <tr>";
			$body .= "      <td colspan=3 bgcolor=#51aa04 height=2><br></td>";
			$body .= "    </tr>";
			$body .= "    <tr>";
			$body .= "      <td width=2 bgcolor=#51aa04><br></td>";
			$body .= "      <td valign=top width=580 height=100>";
			$body .= "<a href=http://www.brt-e.com target=_blank><img src=http://www.brt-e.com/images/darkgreen/schneider_logo.gif vspace=18 border=0 hspace=15></a></td>";
			$body .= "      <td width=2 bgcolor=#51aa04><br></td>";
			$body .= "    </tr>";
			$body .= "  </thead>";
			$body .= "  <tbody>";
			$body .= "    <tr>";
			$body .= "      <td rowspan=3 width=2 bgcolor=#51aa04></td>";
			$body .= "      <td><table width=580 border=0 cellpadding=10 cellspacing=0>";
			$body .= "        <tbody>";
			$body .= "          <tr>";
			$body .= "            <td valign=top><p><strong>尊敬的用户</strong>".$userName."<strong>您好!</strong><br>";
			$body .= "                      <br>";
			$body .= "感谢您注册施耐德电气网上商城(<a href=http://www.brt-e.com target=_blank>http://www.brt-e.com</a>) ，我们将为您提供最贴心的服务，祝您购物愉快！请等待管理员的审核，审核后会有手机短信发到您手机上。右侧是您的注册信息：</p>";
			$body .= "<p><br>";
			$body .= "<strong>您可以随时进入会员中心查看或者更新个人资料</strong><br>";
			$body .= "我们保证每一位客户资料的安全与保密，您可以随时进入会员中心查看和修改个人注册信息，我们也会即时的根据您的最新资料和您保持畅通的沟通。</p>";
			$body .= "<p><br>";
			$body .= "<strong>给会员的一封信</strong><br>";
			$body .= "如何在琳琅满目的电子商务网站中找到让您放心的产品？ 担心买到假货？ 希望得到最权威的产品技术信息，但是没有可靠途径？ 施耐德电气网上商城为您带来安心和安全。我们将通过质量上乘的产品和贴心的服务 保障每一个家庭的用电安全。</p></td>";
			$body .= "<td valign=top><table width=100% bgcolor=#ffffff border=0 cellpadding=0 cellspacing=0>";
			$body .= "<tbody>";
			$body .= "<tr>";
			$body .= "<td width=190 align=center>";
			$body .= "<table width=100% align=center bgcolor=#51aa04 border=0 cellpadding=1 cellspacing=0>";
			$body .= "<tbody>";
			$body .= "<tr>";
			$body .= "<td><table width=100% align=center bgcolor=#ffffff border=0 cellpadding=3 cellspacing=0>";
			$body .= "<tbody>";
			$body .= "<tr>";
			$body .= "<td align=center bgcolor=#ecf4e9><strong>您的个人信息</strong><br>";
			$body .= "<br>";
			$body .= "请妥善保管个人注册信息</td>";
			$body .= "</tr>";
			$body .= "<tr>";
			$body .= "<td bgcolor=#ffffee><table width=100% align=left border=0 cellpadding=2 cellspacing=0>";
			$body .= "<tbody>";
			$body .= "<tr>";
			$body .= "<td><strong>用户名</strong>：".$userName."</td>";
			$body .= "</tr>";
			$body .= "<tr>";
			$body .= "<td><strong>Email</strong>：".$email."</td>";
			$body .= "</tr>";
			$body .= "</tbody>";
			$body .= "</table></td>";
			$body .= "</tr>";
			$body .= "<tr>";
			$body .= "<td align=center bgcolor=#ffffee></td>";
			$body .= "</tr>";
			$body .= "</tbody>";
			$body .= "</table></td>";
			$body .= "</tr>";
			$body .= "</tbody>";
			$body .= "</table></td>";
			$body .= "</tr>";
			$body .= "</tbody>";
			$body .= "</table>";
			$body .= "</td>";
			$body .= "</tr>";
			$body .= "</tbody>";
			$body .= "</table></td>";
			$body .= "<td rowspan=3 width=2 bgcolor=#51aa04></td>";
			$body .= "</tr>";
			$body .= "<tr valign=top>";
			$body .= "<td bgcolor=#51aa04 height=10></td>";
			$body .= "</tr>";
			$body .= "<tr valign=top>";
			$body .= "<td colspan=3 align=center><table border=0 cellpadding=10 cellspacing=0>";
			$body .= "<tbody>";
			
			$body .= "<tr>";
			$body .= "<td valign=top>■重要信息：由于此邮件包含个人注册资料，请妥善保存！<br>";
			$body .= "【注意】本邮件为系统自动发送的邮件，请不要回复本邮件。<br/>";
			$body .= "波普瑞（北京）科技有限公司<br/>";
			$body .= "地址：北京市朝阳区望京科技园区望京东路8号锐创国际商务中心B座510室<br/>";
			$body .= "邮编：100102<br/>";
			$body .= "电话：010-84730103      010-57839238/39<br/>";
			$body .= "传真：010-84730132<br/>";
			$body .= "热线：400-810-1316<br/>";
			$body .= "网址：www.brt-e.com";
			
			$body .= "</td>";
			$body .= "</tr>";
			$body .= "</tbody>";
			$body .= "</table></td>";
			$body .= "</tr>";
			$body .= "<tr valign=top>";
			$body .= "<td colspan=3 width=580 bgcolor=#51aa04 height=10></td>";
			$body .= "</tr>";
			$body .= "</tbody>";
			$body .= "</table>";

		
			
			$this->sendMail($user['email'], $user['realName'], $subject, $body);
			
			$this->message('恭喜您注册成功，等待管理员审核。', GODHOUSE_DOMAIN_WWW);
		}
		$areaList = $this->AreaModel->findAll("fId='1'", 0, 0, "id ASC");
		$this->view->assign('areaList', $areaList);
		$this->display('site_register');
	}
	
	// 登录
	public function actionLogin() {
		session_start();
		$submitTo = getgpc('submitTo', 'P');
		if($submitTo) {
			// 登录成功，跳到哪个页面去
			$tourl = getgpc('tourl', 'R');
			if(!$tourl) {
				$tourl = $_SERVER['HTTP_REFERER'];
				if(strpos($tourl, 'site-login.htm') !== FALSE) {
					$tourl = GODHOUSE_DOMAIN_WWW.'user.htm';
				}
			}
			
			$userName = getgpc('userName', 'P');
			$passwd = getgpc('passwd', 'P');
			$validCode = getgpc('validCode', 'P');
			$expiresTime = getgpc('expiresTime', 'P');
			!$expiresTime && $expiresTime = 1;
			
			if(!$userName || $userName==' Enter Email ...' || $passwd==' password' || !$passwd) {
				$this->message('用户名或密码不能为空！', 'site-login.htm');
			}
			if($validCode != $_SESSION['god_vercode']) {
				$this->message('验证码错误', 'site-login.htm');
			}
			$user = $this->UserModel->find("userName='".daddslashes($userName)."' AND passwd='".md5($passwd)."'");
			if($user) {
				if($user['groupId']<GODHOUSE_GROUP_ADMIN_LIMIT) {
					$this->message('登录失败，您没有登录的权限。', $tourl);
				}
				
				if($user['status'] == GODHOUSE_STATUS_UNVERIFIED) {
					$this->message('登录失败，请等待管理员的审核。', $tourl);
				} elseif($user['status'] == GODHOUSE_STATUS_PAUSED) {
					$this->message('登录失败，您的帐号已被管理员暂停，有问题请联系管理员。', $tourl);
				} elseif ($user['status'] != GODHOUSE_STATUS_VERIFIED) {
					$this->message('登录失败，您帐户异常，有问题请联系管理员。', $tourl);
				}
				
				$this->setStateInfo($user, $expiresTime);
				$this->UserModel->updateByPk($user['userId'], array('lastLoginTime'=>$this->time, 'lastLoginIp'=>$this->onlineip));
				$this->message('登录成功。', $tourl);
			} else {
				$this->message('用户名和密码错误。', $tourl);
			}
		}
		$this->display('site_login');
	}
	
	public function actionAjaxCity() {
		$fId = getgpc(2);
		
		$areaList = $this->AreaModel->findAll("fId='$fId'");
		
		$str = '<select name="user[areaId]" id="city" style="width: 150px;">';
		foreach($areaList as $v) {
			$str .= '<option value="'.$v['id'].'">'.$v['name'].'</option>';
		}
		$str .= '</select>';
		$this->message($str);
	}
	
	/* 找回密码 */
	public function actionRecoveredPwd() {
		//phpinfo();
		$msg = '';
		if($this->getState('isRepeat')) {
			$this->message('24小时内只能找回一次密码。', GODHOUSE_DOMAIN_WWW);
		}
		if(getgpc(2)) {
			$email = getgpc('email');
			if(!$email) {
				$this->message('请输入邮箱。', GODHOUSE_DOMAIN_WWW.'site-recoveredPwd.htm');
			}
			$user = $this->UserModel->find("email='".daddslashes($email)."'");
			if(!$user) {
				$this->message('邮箱不存在。', GODHOUSE_DOMAIN_WWW.'site-recoveredPwd.htm');
			}
			$time = $this->time + 10*60;	//十分钟之内有效
			$code = sid_encode(md5(GODHOUSE_KEY.$user['userId']).'|'.$time);
			$url = GODHOUSE_DOMAIN_WWW.'site-resetPwd.htm?userId='.$user['userId'].'&code='.$code;
			$this->setState('recoveredPwd', 1);
			$this->setState('isRepeat', 1);
			
			$returnUrl = GODHOUSE_DOMAIN_WWW.'site-recoveredPwd.htm';
			$subject = "密码找回！";
			$body = "请您在十分钟内点击或复制下面的URL进行重新修改密码！<br/><a href=\"$url\" target=\"_blank\">".$url."</a>";
			$this->sendMail($user['email'], $user['realName'], $subject, $body, $returnUrl);
		}
		$this->view->assign('msg', $msg);
		$this->display('site_recoveredPwd');
	}
	
	/* 重置密码 */
	public function actionResetPwd() {
		$userId = getgpc('userId', 'R');
		$code = getgpc('code', 'R');
		
		if (!$this->getState('recoveredPwd')) {
			$this->message('出现错误，请您重新找回密码。', GODHOUSE_DOMAIN_WWW);
		}
		$codestr = sid_decode($code);
		$time = 0;
		$vcode = '';
		if($codestr) {
			$r = explode('|', $codestr);
			$vcode = $r[0];
			$time = $r[1];
		}
		if($vcode != md5(GODHOUSE_KEY.$userId)) {
			$this->message('认证码不对。', GODHOUSE_DOMAIN_WWW);
		}
		if($time < $this->time) {
			$this->message('已过期。', GODHOUSE_DOMAIN_WWW);
		}
		
		if (getgpc('submitTo', 'P')) {
			$passwd = getgpc('passwd', 'P');
			$this->UserModel->updateByPk($userId, array(
				'passwd'=>md5($passwd),
			));
			$this->setState('recoveredPwd', NULL);
			$this->message('修改成功，请登录。', GODHOUSE_DOMAIN_WWW.'site-login.htm');
		}
		$this->view->assign('userId', $userId);
		$this->view->assign('code', $code);
		$this->display('site_resetPwd');
	}
	
	/* 退出登录 */
	public function actionLogout() {
		$user = array(
			'userId'=>NULL,
			'userName'=>NULL,
			'groupId'=>NULL,
		);
		$this->setStateInfo($user, 0);
		$this->message('退出成功', 'index.htm');
	}
	
	// 检查用户名是否存在
	public function actionCheckUser() {
		$userName = getgpc('userName');
		if(!$userName) {
			$this->message('&nbsp;&nbsp;&nbsp;&nbsp;帐号只能为英文或加数字。');
		}
		if(!ctype_alnum($userName)) {
			$this->message('&nbsp;&nbsp;&nbsp;&nbsp;错误，帐号范围a_zA_Z0_9。');
		}
		$user = $this->UserModel->find("userName='$userName'");
		if($user) {
			$this->message('&nbsp;&nbsp;&nbsp;&nbsp;您输入的帐号已存在，请您重新输入。');
		} else {
			$this->message('&nbsp;&nbsp;&nbsp;&nbsp;恭喜您“'.$userName.'”可以注册。');
		}
	}
	
	/**
	 * 发送邮件
	 *
	 * @param unknown_type $email 邮件
	 * @param unknown_type $realName 姓名
	 * @param unknown_type $subject	主题
	 * @param unknown_type $body 正文
	 * @param unknown_type $returnUrl 返回URL
	 */
	private function sendMail($email, $realName, $subject, $body, $returnUrl='') {
		require(GODHOUSE_ROOT.'library/phpmailer/class.phpmailer.php');
		require(GODHOUSE_ROOT.'library/phpmailer/class.smtp.php'); // 可选
		
		$mail = new PHPMailer();
		
		//$body = $mail->getFile('contents.html');//邮件正文内容，提取html文件为其内容
		//$body = eregi_replace("[\]",'',$body);
		$mail->CharSet = "utf-8";  
		$mail->IsSMTP();
		$mail->SMTPAuth = true; 	// 必填，SMTP服务器是否需要验证，true为需要，false为不需要
		$mail->Host = "smtp.163.com";	//必填，设置SMTP服务器
		$mail->Port = 25; // 设置端口
		
		$mail->Username = "test_brt@163.com"; // 必填，开通SMTP服务的邮箱；任意一个126邮箱均可
		$mail->Password = "testtest"; //必填， 以上邮箱对应的密码
		
		$mail->From = 'test_brt@163.com'; //必填，发件人Email
		$mail->FromName = '施耐德电气网上商城-波普瑞'; //必填，发件人昵称或姓名
		$mail->Subject = $subject; //必填，邮件标题（主题）
		$mail->AltBody = "text/html"; 
		$mail->WordWrap = 50; // 自动换行的字数
		
		$mail->MsgHTML($body);
		
		$mail->AddReplyTo("test_brt@163.com", GODHOUSE_SITENAME);
		
		//$mail->AddAttachment("/path/to/file.zip"); // 添加附件
		//$mail->AddAttachment("/path/to/image.jpg","new.jpg"); // 添加附件
		$mail->AddAddress($email, $realName);//参数一：收信人的邮箱地址，可添加多个。参数二：收件人称呼
		$mail->IsHTML(true); // 是否以HTML形式发送，如果不是，请删除此行
		
		$result = $mail->Send();
		if($returnUrl) {
			if(!$result) {
				$msg = "Mailer错误: ". $mail->ErrorInfo;
				$this->message($msg, $returnUrl);
			} else {
				$this->message('邮件已发送成功！由于个别邮箱的拦截功能，该邮件有可能被误处理为垃圾邮件，请您仔细查找！', $returnUrl);
			}
		}
	}
}